package org.seckill.service.impl;

import org.apache.commons.collections.MapUtils;
import org.seckill.dao.SeckillDao;
import org.seckill.dao.SuccessKillDao;
import org.seckill.dao.cache.RedisDao;
import org.seckill.dto.Exposer;
import org.seckill.dto.SeckillExecution;
import org.seckill.entity.Seckill;
import org.seckill.entity.SuccessKill;
import org.seckill.enums.SeckillStatEnum;
import org.seckill.exception.RepateKillException;
import org.seckill.exception.SeckillCloseException;
import org.seckill.exception.SeckillException;
import org.seckill.service.SeckillService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class SeckillServiceImpl implements SeckillService {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private SeckillDao seckillDao;

    @Autowired
    private SuccessKillDao successKillDao;

    @Autowired
    private RedisDao redisDao;

    //混淆MD5 盐值
    private final String slat = "121oiansdnasioda9e0asdai0s9da(*^*&%";

    @Override
    public List<Seckill> getSeckillList() {
        return seckillDao.queryAll(0, 4);
    }

    @Override
    public Seckill getById(long seckillId) {
        return seckillDao.queryById(seckillId);
    }

    @Override
    public Exposer exportSeckillUrl(long seckillId) {
        //优化点 ， 缓存优化
        Seckill seckill = redisDao.getSeckill(seckillId);
        if(seckill == null){
            //从数据库查找
            seckill =  seckillDao.queryById(seckillId);
            // 秒杀记录不存在
            if (seckill == null) {
                return new Exposer(false, seckillId);
            }else{
                redisDao.setSeckill(seckill);
            }
        }
        Date start = seckill.getStartTime();
        Date end = seckill.getEndTime();
        Date now = new Date();
        //秒杀还没开始 或者 已经结束
        if (now.getTime() < start.getTime() || now.getTime() > end.getTime()) {
            return new Exposer(false, seckillId, now.getTime(), start.getTime(), end.getTime());
        }
        //返回秒杀url
        String md5 = getMD5(seckillId);

        return new Exposer(true, md5, seckillId);
    }

    @Override
    @Transactional
    public SeckillExecution excuteSeckill(long seckillId, long userPhone, String md5) throws SeckillException, RepateKillException, SeckillCloseException {
        try {
            if (StringUtils.isEmpty(md5) || !md5.equals(getMD5(seckillId))) {
                throw new SeckillException("seckill data rewire");
            }
            //执行秒杀逻辑  1.减库存
            Date nowTime = new Date();
            int updateCount = seckillDao.reduceNumber(seckillId, nowTime);
            if (updateCount <= 0) {
                throw new SeckillCloseException("seckill is closed ");
            } else {
                //记录购买行为
                int insertCount = successKillDao.insertSuccessKill(seckillId, userPhone);
                if (insertCount <= 0) {
                    throw new RepateKillException(" repate seckill ");
                } else {
                    //秒杀成功
                    SuccessKill successKill = successKillDao.queryByIdWithSecckill(seckillId, userPhone);
                    return new SeckillExecution(seckillId, SeckillStatEnum.SUCCESS, successKill);
                }
            }
        } catch (SeckillCloseException e1) {
            throw e1;
        } catch (RepateKillException e2) {
            throw e2;
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw new SeckillException("seckill inner error " + e.getMessage());
        }
    }

    @Override
    public SeckillExecution excuteSeckillProcedure(long seckillId, long userPhone, String md5)  {
        if (StringUtils.isEmpty(md5) || !md5.equals(getMD5(seckillId))) {
            return new SeckillExecution(seckillId,SeckillStatEnum.DATA_REWRITE);
        }
        Date killTime = new Date();

        Map<String,Object> paramMap = new HashMap<String,Object>();
        paramMap.put("seckillId",seckillId);
        paramMap.put("phone",userPhone);
        paramMap.put("killTime",killTime);
        paramMap.put("result",null);
        try {
            //执行存储过程，result被赋值
            seckillDao.killByProcedure(paramMap);
            int result = MapUtils.getInteger(paramMap,"result",-2);
            if(result == 1){
                //秒杀成功
                SuccessKill successKill = successKillDao.queryByIdWithSecckill(seckillId,userPhone);
                return new SeckillExecution(seckillId,SeckillStatEnum.SUCCESS,successKill);
            }else{
                return new SeckillExecution(seckillId,SeckillStatEnum.indexOf(result));
            }
        }catch (Exception e){
            logger.error(e.getMessage(),e);
            return new SeckillExecution(seckillId,SeckillStatEnum.INNER_ERROR);
        }
    }

    //生成md5 规则
    private String getMD5(long seckillId) {
        String base = seckillId + "/" + slat;
        String md5 = DigestUtils.md5DigestAsHex(base.getBytes());
        return md5;
    }
}
